package chat.keepWind;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;
import org.jb2011.lnf.beautyeye.ch16_tree.__IconFactory__;

import chat.keepWind.bean.Config;
import chat.keepWind.bean.DataPackage;
import chat.keepWind.bean.User;
import chat.keepWind.event.ReceiveDataPackage;
import chat.keepWind.event.SendMessage;
import chat.keepWind.event.SendOnline;
import chat.keepWind.ui.ChatMainUI;
import chat.keepWind.ui.ChatUI;
import chat.keepWind.ui.FriendTree;
import chat.keepWind.ui.IpTableUI;
import chat.keepWind.ui.JTreeBean;
import chat.keepWind.util.ChatUtil;
import chat.keepWind.util.FileUtil;
import chat.keepWind.util.GlobalConst;
import chat.keepWind.util.NetUtil;
import io.netty.util.CharsetUtil;


public class App {

	private JFrame frame;
	private FriendTree userTree;
	private Map<String,ChatUI> chats = new HashMap<>();
	//初始化 在线用户列表
    private List<User> onlineUsers = new ArrayList<>();
	private String myIP = "";
	private Config config = new Config();

	public static void main(String[] args) {
		new App();

	}

	public App() {
		ChatUtil.dataMap.put("chats", chats);
		
	
		myIP = NetUtil.getLocalIp();
		
		ChatUtil.dataMap.put("ip", myIP);
			
		ChatUtil.dataMap.put("onlineUsers", onlineUsers);
		//初始化文件夹与配置文件
		initFile();
		// 初始化用户界面
		initChatMain();
		ChatUtil.dataMap.put("userTree", userTree);
		// 发送局域网内 其他在线用户的 上线消息
		pushOnlineInfo();
		//加入在线用户列表
		userTree.addAllUser(onlineUsers);
		// 初始化接受消息服务 
		new Thread(new Runnable() {
			public void run() {
				runServer();
			}
		}).start();
	}

	/**
	 * 初始化 界面
	 */
	private void initChatMain(){
		try {
			BeautyEyeLNFHelper.launchBeautyEyeLNF();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		  UIManager.put("RootPane.setupButtonVisible", false);
		  //节点 展开，关闭 图标设置
		  UIManager.put("Tree.expandedIcon",__IconFactory__.getInstance().getTreeB());
		  UIManager.put("Tree.collapsedIcon",__IconFactory__.getInstance().getTreeA());
		  
	      final ChatMainUI ui = new ChatMainUI();
	      frame = ui.getwinFrame();
	      userTree = new FriendTree();
	      ui.setFriend(userTree.initTree());
	     
	      frame.setVisible(true);
	      //userTree.addOnlineUser("34.1.172.149","34.1.172.149");
	      
	      userTree.getTree().addMouseListener(new MouseAdapter() {
		
				public void mousePressed(MouseEvent e) {
				
					TreePath selPath = userTree.getTree().getPathForLocation(e.getX(), e.getY());
					if(selPath==null){
						return;
					}
					DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
					final JTreeBean tbean = (JTreeBean) node.getUserObject();
					final String ip  = tbean.getIp();
					final String nickName = tbean.getNick();
					
					if(ip.equals("Group")){
						return;
					}
					
					if (e.getClickCount() == 2) {
						/*JTree tree = (JTree) e.getSource();
						int rowLocation = tree.getRowForLocation(e.getX(), e.getY());
						TreePath treepath = tree.getPathForRow(rowLocation);
						DefaultMutableTreeNode treenode = (DefaultMutableTreeNode) treepath
								.getLastPathComponent();
						JTreeBean jtb = (JTreeBean) treenode.getUserObject();
						String id = jtb.getString();
						if(id.equals("Group")
								||id.equals("在线用户")){
							return;
						}*/
						if(ip.equals("在线用户")){
							return;
						}
						
						ChatUtil.openChat(ip,nickName);
						
					}
					if (SwingUtilities.isRightMouseButton(e)) {
						JPopupMenu popupMenu = new JPopupMenu();
						
						if(ip.equals("在线用户")){
							JMenuItem userListItem = new JMenuItem();
							userListItem.setText("刷新用户列表");
							popupMenu.add(userListItem);
							userListItem.addActionListener(new ActionListener(){
								@Override
								public void actionPerformed(ActionEvent e) {
									onlineUsers.clear();
									userTree.delAllUser();
									pushOnlineInfo();
									userTree.addAllUser(onlineUsers);
								}
							});
						}else{
							JMenuItem chatMenuItem = new JMenuItem();
							JMenuItem broInfoMenuItem = new JMenuItem();
							JMenuItem remarkMenuItem = new JMenuItem();
						
							chatMenuItem.setText("聊天");
							broInfoMenuItem.setText("查看IP");
							remarkMenuItem.setText("备注");
							
							popupMenu.add(chatMenuItem);
							popupMenu.add(broInfoMenuItem);
							popupMenu.add(remarkMenuItem);
							
							
							chatMenuItem.addActionListener(new ActionListener(){
								@Override
								public void actionPerformed(ActionEvent e) {
									ChatUtil.openChat(ip,nickName);
								}
							});
							broInfoMenuItem.addActionListener(new ActionListener(){

								@Override
								public void actionPerformed(ActionEvent e) {
									JOptionPane.showMessageDialog(frame, ip, "用户IP地址", 1);
									
								}
							});
							
							remarkMenuItem.addActionListener(new ActionListener(){
								@Override
								public void actionPerformed(ActionEvent e) {
									String nickName = JOptionPane.showInputDialog(frame,"", "备注", 3);
									User tmp = ChatUtil.isExsitsIp(onlineUsers, ip); 
									
									if(tmp==null || nickName==null || 
											"".equals(nickName.trim())){
										return;
									}
									//保存配置
									//Config config = (Config)ChatUtil.dataMap.get("config");
									Map<String,User> userMap = config.getUserMap();
									User u = userMap.get(ip);
									if(u==null){
										u = new User();
										u.setIp(ip);
										u.setNickName(nickName.trim());
										userMap.put(ip, u);
									}else{
										u.setNickName(nickName.trim());
									}
									tbean.setNick(nickName.trim());
									try {
										FileUtil.writeConfig(config);
									} catch (IOException e1) {
										e1.printStackTrace();
									}
									//更新在线用户集合
									tmp.setNickName(nickName.trim());
								}
							});
							
						}
						
						try {
							popupMenu.show(e.getComponent(), e.getX(), e.getY());
						} catch (Exception ecast) {
							ecast.printStackTrace();
							return;
						}
					}
				}
			});
			
	       //双击头像，修改昵称
	      ui.getjLabel_ui().addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e) {
					if (e.getClickCount() == 2) {
						String nickName = JOptionPane.showInputDialog(frame,"请输入昵称", "修改昵称", 3);
						if(nickName==null || 
								"".equals(nickName.trim())){
							return;
						}
						config.setLocalNickName(nickName.trim());
						try {
							FileUtil.writeConfig(config);
						} catch (IOException e1) {
							e1.printStackTrace();
						}
						ui.getheadpic().setText(config.getLocalNickName());
					}
				}
			});
			//添加IP网段
	      	ui.getAddIpBtn().addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					JTextField startIp = new JTextField(14);
				    JTextField endIp = new JTextField(14);

				    JPanel myPanel = new JPanel();
				    myPanel.add(new JLabel("起:"));
				    myPanel.add(startIp);
				    //myPanel.add(Box.createHorizontalStrut(15));
				    myPanel.add(new JLabel("止:"));
				    myPanel.add(endIp);

				    /*int result = JOptionPane.showConfirmDialog(frame, myPanel,
				        "请输入起止IP地址", JOptionPane.OK_CANCEL_OPTION);*/
				    String[] options = {"  保存  ","  关闭  "};
				    int result = JOptionPane.showOptionDialog(frame, myPanel, "请输入起止IP地址",
				    		JOptionPane.OK_CANCEL_OPTION, 3, null,
				    			options, "");
				    if (result == JOptionPane.OK_OPTION) {
				    	if(startIp.getText()==null
				    			|| "".equals(startIp.getText().trim())||endIp.getText()==null
						    			|| "".equals(endIp.getText().trim())){
				    		JOptionPane.showMessageDialog(frame, "不能为空！");
				    		return;
				    	}
				    	String ip1 = startIp.getText().trim();
				    	String ip2 = endIp.getText().trim();
				    	
						if(!NetUtil.checkIp(ip1)||!NetUtil.checkIp(ip2)){
							JOptionPane.showMessageDialog(frame, "IP格式不正确！");
				    		return;
						}
						int last1 = ip1.lastIndexOf(".");
						int last2 = ip2.lastIndexOf(".");
						if(!ip1.substring(0,last1).equals(ip2.substring(0,last2))){
							JOptionPane.showMessageDialog(frame, "起止IP不在同一网段！");
				    		return;
						}
						String lastStr1 = ip1.substring(last1+1,ip1.length());
						String lastStr2 = ip2.substring(last2+1,ip2.length());
						if(lastStr2.compareTo(lastStr1)<0){
							JOptionPane.showMessageDialog(frame, "截止IP不能小于起始IP！");
				    		return;
						}
						String item = ip1+"---"+ip2;
						config.getIps().add(item);
						
						try {
							FileUtil.writeConfig(config);
						} catch (IOException e1) {
							e1.printStackTrace();
						}
						pushOnlineInfo3(item);
						//重新渲染用户列表
						userTree.delAllUser();
						userTree.addAllUser(onlineUsers);
				    }
					
				}
	      	});
	      	//查看已添加的IP网段
	      	ui.getQueryIpBtn().addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					final List<String> ips = config.getIps();
				
					if(ips.size()>0){
						Object[][] tableData = new Object[ips.size()][2];
						for(int i=0;i<ips.size();i++){
							tableData[i][0] = false;
							tableData[i][1] = ips.get(i);
						}
						
						final IpTableUI iptab = new IpTableUI(tableData);
						
						iptab.getJbut().addActionListener(new ActionListener() {
							@Override
							public void actionPerformed(ActionEvent e) {
								
								int row = iptab.getTable().getRowCount();
								int num=0;
								for(int i=0;i<row;i++){
									boolean ck = (Boolean)iptab.getModel().getValueAt(i-num, 0);
									String ipstr = (String)iptab.getModel().getValueAt(i-num, 1);
									if(ck){
										iptab.getModel().removeRow(i-num);
										ips.remove(ipstr);
										num++;
									}
								}
								if(num>0){
									try {
										FileUtil.writeConfig(config);
									} catch (IOException e1) {
										e1.printStackTrace();
									}
								}
							}
						});
					}else{
						JOptionPane.showMessageDialog(frame, "还没有添加网段！");
					}
					
				}
	      		
	      	});
			// 关闭窗口时事件，发送下线消息
			frame.addWindowListener(new WindowAdapter() {
				@SuppressWarnings("unchecked")
				public void windowClosing(WindowEvent e) {
					DataPackage data = null;
					List<User> users = (List<User>)ChatUtil.dataMap.get("onlineUsers");
					for(User user:users){
						String ip = user.getIp();
						
						data = new DataPackage();
						data.setFromIp(myIP);
						data.setToIp(ip);
						data.setNickName(config.getLocalNickName());
						data.setMsgType(GlobalConst.TYPE_LOGOUT);
						data.setMsgContent("下线".getBytes(CharsetUtil.UTF_8));
						
						SendMessage snd = new SendMessage();
						snd.send(ip, data);
					}
					System.exit(0);// 退出程序
				}
			});
	}

	/**
	 * 发送局域网内 其他在线用户的 上线消息
	 */
	private void pushOnlineInfo(){
		List<String> onlineIps = NetUtil.getLanIPs();
		DataPackage data = null;
		for(String ip:onlineIps){
			data = new DataPackage();
			data.setFromIp(myIP);
			data.setToIp(ip);
			data.setNickName(config.getLocalNickName());
			data.setMsgType(GlobalConst.TYPE_LOGIN);
			data.setMsgContent("上线".getBytes(CharsetUtil.UTF_8));
			
			SendOnline snd = new SendOnline();
			
			snd.send(ip, data);
		}
		//新增的网段，上线信息推送
		pushOnlineInfo2();
		
		/*DataPackage data = new DataPackage();
		data.setFromIp(myIP);
		data.setToIp(myIP);
		data.setMsgType(GlobalConst.TYPE_LOGIN);
		data.setMsgContent("上线".getBytes(CharsetUtil.UTF_8));
		data.setFileName("1.doc");
		SendOnline snd = new SendOnline();
		snd.send("127.0.0.1", data);*/
		
	}
	/**
	 * 发送局域网内新增网段，在线用户的 上线消息
	 */
	private void pushOnlineInfo2(){
		List<String> custIps = config.getIps();
		DataPackage data = null;
		if(custIps.size()>0){
			for(String item:custIps){
				String[] arr = item.split("---");
				
				int lastIdx1 = arr[0].lastIndexOf(".");
				int lastIdx2 = arr[1].lastIndexOf(".");
				String preStr = arr[0].substring(0,lastIdx1);
				int lastNum1 = Integer.valueOf(arr[0].substring(lastIdx1+1,arr[0].length()));
				int lastNum2 = Integer.valueOf(arr[1].substring(lastIdx2+1,arr[1].length()));
				int len = lastNum2-lastNum1+1;
				for(int i=0;i<len;i++){
					data = new DataPackage();
					data.setFromIp(myIP);
					data.setToIp(preStr+"."+(lastNum1+i));
					data.setNickName(config.getLocalNickName());
					data.setMsgType(GlobalConst.TYPE_LOGIN);
					data.setMsgContent("上线".getBytes(CharsetUtil.UTF_8));
					
					SendOnline snd = new SendOnline();
					snd.send(data.getToIp(), data);
					
				}
			}
		}
	}
	/**
	 * 发送局域网内  刚新增的网段，在线用户的 上线消息
	 */
	private void pushOnlineInfo3(String ip){
		
		DataPackage data = null;
			
		String[] arr = ip.split("---");
		
		int lastIdx1 = arr[0].lastIndexOf(".");
		int lastIdx2 = arr[1].lastIndexOf(".");
		String preStr = arr[0].substring(0,lastIdx1);
		int lastNum1 = Integer.valueOf(arr[0].substring(lastIdx1+1,arr[0].length()));
		int lastNum2 = Integer.valueOf(arr[1].substring(lastIdx2+1,arr[1].length()));
		int len = lastNum2-lastNum1+1;
		
		for(int i=0;i<len;i++){
			data = new DataPackage();
			data.setFromIp(myIP);
			data.setToIp(preStr+"."+(lastNum1+i));
			data.setNickName(config.getLocalNickName());
			data.setMsgType(GlobalConst.TYPE_LOGIN);
			data.setMsgContent("上线".getBytes(CharsetUtil.UTF_8));
			
			SendOnline snd = new SendOnline();
			snd.send(data.getToIp(), data);
			
		}	
	}
	private void initFile(){
		File file = new File(GlobalConst.CAP_IMG_PATH);
		if(!file.exists()){
			file.mkdirs();
		}else{//清空截图
			File[] subFiles = file.listFiles();
			for(File f : subFiles){
				f.delete();
			}
		}
		file = new File(GlobalConst.TMP_ROOT_PATH+"keepWindIM"
				+File.separator+"config.ser");
		if(!file.exists()){
			try{
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			config.setLocalNickName(myIP);//默认 昵称为IP地址
			try {
				FileUtil.writeConfig(config);
			} catch (IOException e) {
				e.printStackTrace();
			}
			ChatUtil.dataMap.put("config", config);
		}else{
			try {
				config = FileUtil.readConfig();
			} catch (ClassNotFoundException | IOException e) {
				e.printStackTrace();
			}
			ChatUtil.dataMap.put("config", config);
		}
	}
	/**
	 * 开启 接受消息服务
	 */
	private void runServer(){
		System.out.println("开启接受消息服务");
		new ReceiveDataPackage().listen();
	}
	
	
}
